package com.bodacn.keypoint;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.text.InputType;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpResponseException;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.lang.reflect.Field;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

public class GuideActivity extends AppCompatActivity implements View.OnClickListener {
    private final static String TAG = GuideActivity.class.getSimpleName();
    private Button btn_LoginSYS, btn_ExitSYS;
    private ImageButton btn_guide_setup,btn_EditPass;
    private EditText edit_LoginUserNo;
    private TextView txt_CPUID,txt_SoftVer;
    //全局提示;
    Toast curToast;
    //初始化定时器;
    private Timer netTimer;
    private TimerTask  netTimeTask;
    //全局变量
    String STORE_NAME = "Settings";
    String serviceUrl="http://10.10.60.2/BDCOMM";
    String serviceUrlExt  = "/BDService.asmx?wsdl";
    String CPUID,curLoginUserNo,curLoginUser,curFactory, curDepartNo,curDepart,curLoginTime ,language="中文",curUserPower,curTime;//操作员所属部门等信息;
    int curOperateTime =600;//工作分钟
    int curPlaceCount=60;//工位数;
    private JSONArray loginJSONArray;//用于接收登陆返回信息;
    private ProgressDialog waitDialog = null;
    private final static int MSG_ChangePSWOver=9001;
    private final static int MSG_LoginCheckOver=9002;
    private final static int MSG_AllowScan=9003;
    private final static int MSG_CheckNetWork=9004;
    //核心设置的代码
    protected void switchLanguage() {
        //读取配置文件-设置语言
        SharedPreferences settings = getSharedPreferences(STORE_NAME, MODE_PRIVATE);
        serviceUrl=settings.getString("serviceUrl",serviceUrl);
        MyApplication.UrlApi=settings.getString("UrlApi",MyApplication.UrlApi);
        language=settings.getString("language",language);
        //获取资源
        Resources resources = getResources();
        Configuration config = resources.getConfiguration();
        DisplayMetrics dm = resources.getDisplayMetrics();
        switch (language) {
            case "zh":
                config.locale = new Locale("zh","");
                resources.updateConfiguration(config, dm);
                break;
            case "en":
                config.locale = new Locale("en","");
                resources.updateConfiguration(config, dm);
                break;
            case "km":
                config.locale = new Locale("km","");
                resources.updateConfiguration(config, dm);
                break;
            default:
                config.locale = new Locale("zh","");
                resources.updateConfiguration(config, dm);
                break;
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //重设界面语言
        switchLanguage();
        //创建界面;
        setContentView(R.layout.activity_guide);
        initView();
        try {
            String SoftVer=getVersionName();
            txt_SoftVer.setText("VER:"+SoftVer);
        } catch (Exception e) {
            e.printStackTrace();
        }
        hideBottomUIMenu();
    }


    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏状态栏和底部虚拟按键
        View decorView = getWindow().getDecorView();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            int flag = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
            decorView.setSystemUiVisibility(flag);
        }
    }
    @Override
    protected void onRestart() {
        super.onRestart();
        edit_LoginUserNo.setText("");
        edit_LoginUserNo.selectAll();
        edit_LoginUserNo.requestFocus();
        edit_LoginUserNo.requestFocusFromTouch();

    }

    private void initView()
    {
        txt_CPUID=(TextView)findViewById(R.id.txt_CPUID);
        txt_SoftVer=(TextView)findViewById(R.id.txt_SoftVer);
        //按键;
        btn_LoginSYS=(Button)findViewById(R.id.btn_LoginSYS);
        btn_LoginSYS.setOnClickListener(this);
        btn_LoginSYS.setFocusableInTouchMode(false);
        btn_LoginSYS.setFocusable(false);
        btn_ExitSYS =(Button)findViewById(R.id.btn_ExitSYS);
        btn_ExitSYS.setOnClickListener(this);
        btn_ExitSYS.setFocusableInTouchMode(false);
        btn_ExitSYS.setFocusable(false);
        btn_guide_setup=(ImageButton)findViewById(R.id.btn_guide_setup);
        btn_guide_setup.setOnClickListener(this);
        btn_guide_setup.setFocusableInTouchMode(false);
        btn_guide_setup.setFocusable(false);
        btn_EditPass=(ImageButton)findViewById(R.id.btn_EditPass);
        btn_EditPass.setOnClickListener(this);
        btn_EditPass.setFocusableInTouchMode(false);
        btn_EditPass.setFocusable(false);
        //显示控制;
        edit_LoginUserNo=(EditText)findViewById(R.id.edit_LoginUserNo);
        edit_LoginUserNo.setInputType(InputType.TYPE_NULL);
        edit_LoginUserNo.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event!=null){
                    if ((event.getAction()==KeyEvent.ACTION_DOWN)&&(event.getKeyCode()== KeyEvent.KEYCODE_ENTER))
                    {
                        loginCheck();
                    }
                }
                return false;
            }
        });
        edit_LoginUserNo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                edit_LoginUserNo.setFocusable(true);
                edit_LoginUserNo.setInputType(InputType.TYPE_CLASS_NUMBER);
                //1.得到InputMethodManager对象
                InputMethodManager imm = (InputMethodManager) getSystemService(GuideActivity.this.INPUT_METHOD_SERVICE);
                //2.调用showSoftInput方法显示软键盘，其中view为聚焦的view组件
                imm.showSoftInput(edit_LoginUserNo,InputMethodManager.SHOW_FORCED);
            }
        });
        edit_LoginUserNo.setFocusableInTouchMode(true);
        edit_LoginUserNo.setFocusable(true);
        edit_LoginUserNo.requestFocus();
        edit_LoginUserNo.requestFocusFromTouch();

        //初始提醒;
        curToast = Toast.makeText(getApplicationContext(), "", Toast.LENGTH_LONG);
        curToast.setGravity(Gravity.CENTER, 0, 0);
        //获取机器ID
//        CPUID=getLocalCPUID().toUpperCase();
//        txt_CPUID.setText(CPUID);
    }


    private void showTips() {
        AlertDialog alertDialog = new AlertDialog.Builder(this)
                .setTitle(getString(R.string.SystemHint)).setMessage(getString(R.string.SystemExitConfirm))
                .setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Intent exit = new Intent(Intent.ACTION_MAIN);
                        exit.addCategory(Intent.CATEGORY_HOME);
                        exit.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(exit);
                        System.exit(0);
                        //finish();
                    }

                }).setNegativeButton(getString(R.string.Cancel),

                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                return;
                            }
                        }).create(); // 创建对话框
        alertDialog.show(); // 显示对话框
    }

    //直接连获取数据，与Handler配套使用;
    private void ReadSQLData(final String SQLComm) {
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try{
                    JSONArray jsonArray  = DBUtil.QuerySQL2JSON(SQLComm);
                    System.out.println(jsonArray);
                    //往界面转数据;
                    if ((jsonArray!=null)&&(jsonArray.length()>0)) {
                        //返回的登陆信息;
                        if (jsonArray.optJSONObject(0).has("LoginCheck")==true)
                        {
                            loginJSONArray=jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_LoginCheckOver;
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);
                        }
                        //返回的登陆信息;
                        if (jsonArray.optJSONObject(0).has("ChangePSW")==true)
                        {
                            loginJSONArray=jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_ChangePSWOver;
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);
                            Log.d("msg","ChangePSW--------------------1");
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Message msg = new Message();
                    msg.what = MSG_AllowScan;
                    handler.removeMessages(msg.what);
                    handler.sendMessage(msg);
                }

            }

        };
        new Thread(run).start();

    }

    //启动定时器;
    private void checkNetTimer(){
        if (netTimer ==null) {
            netTimer = new Timer();
            System.out.println("onCreate timer---------------------------------2.1");
            //定时任务;
            if (netTimeTask == null) {
                netTimeTask = new TimerTask() {
                    @Override
                    public void run() {
                        Message message = new Message();
                        message.what = MSG_CheckNetWork;
                        handler.sendMessage(message);
                    }
                };
            }
            System.out.println("onCreate timer---------------------------------2.2");
            netTimer.schedule(netTimeTask, 1000, 1000);
        }
    }
    //停止计时器;
    private void stopCheckNetTimer(){
        if (netTimer != null) {
            netTimer.cancel();
            netTimer = null;
        }
        if (netTimeTask != null) {
            netTimeTask.cancel();
            netTimeTask = null;
        }
        System.out.println("startTimer five---------------------------------Start");
    }

    //通过消息来执行处理类程序,不更新UI则不一定需要通过这个;
    final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            // TODO Auto-generated method stub
            // 根据消息ID来判断要做的事情
            int msgId = msg.what;
            switch (msgId) {
                case MSG_CheckNetWork:
                    System.out.println("EnterMSG_CheckNetWork");
                    boolean networkState=false;
                    if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.LOLLIPOP){
                        networkState=checkNetState_21();
                    }else{
                        networkState=checkNetState_21orNew();
                    }
                    try {
                        if (networkState==true){
                            stopCheckNetTimer();
                            Log.e(TAG,"serviceUrl"+serviceUrl);
                            //下载最新的版本文件,检查是否需要升级;
                            AutoUpdate autoupdate = new AutoUpdate(getApplicationContext(),"com.bodacn.keypoint");
                            autoupdate.CheckWebUpdate(serviceUrl+"/UPDATE/keypoint.xml");
                        } else{
                            Log.e(TAG,"-----------------------------------------CheckNetWork Err-----------------------------------------");
                        }
                    } catch (Exception e){


                    }
                    break;
                case MSG_ChangePSWOver:
                    Log.d("msg","ChangePSW--------------------1");
                    try {
                        if (loginJSONArray!=null) {
                            if (loginJSONArray.optJSONObject(0).get("ChangePSW").equals("OK")) {
                                curTime = "";
                                if (loginJSONArray.optJSONObject(0).has("Factory"))
                                    curFactory = loginJSONArray.optJSONObject(0).get("Factory").toString();
                                if (loginJSONArray.optJSONObject(0).has("DepartNo"))
                                    curDepartNo = loginJSONArray.optJSONObject(0).get("DepartNo").toString();
                                if (loginJSONArray.optJSONObject(0).has("Depart"))
                                    curDepart = loginJSONArray.optJSONObject(0).get("Depart").toString();
                                if (loginJSONArray.optJSONObject(0).has("PlaceCount"))
                                    curPlaceCount = loginJSONArray.optJSONObject(0).getInt("PlaceCount");
                                if (loginJSONArray.optJSONObject(0).has("LoginUserNo"))
                                    curLoginUserNo = loginJSONArray.optJSONObject(0).get("LoginUserNo").toString();
                                if (loginJSONArray.optJSONObject(0).has("LoginUser"))
                                    curLoginUser = loginJSONArray.optJSONObject(0).get("LoginUser").toString();
                                if (loginJSONArray.optJSONObject(0).has("OperateTime"))
                                    curOperateTime = loginJSONArray.optJSONObject(0).getInt("OperateTime");
                                if (loginJSONArray.optJSONObject(0).has("UserPower"))
                                    curUserPower = loginJSONArray.optJSONObject(0).getString("UserPower");
                                //设置系统时间
                                curToast.setText(getString(R.string.ChangPswOKInfo));
                                curToast.show();
                            } else {
                                curToast.setText(getString(R.string.ChangPswErrInfo));
                                curToast.show();
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                case MSG_LoginCheckOver:
                case MSG_AllowScan:
                    try {
                        if (loginJSONArray!=null) {
                            if (loginJSONArray.optJSONObject(0).getString("LoginCheck").equals("OK")) {
                                String curLoginType = "A";//默认为组长登陆;
                                if (loginJSONArray.optJSONObject(0).has("Factory"))
                                    curFactory = loginJSONArray.optJSONObject(0).get("Factory").toString();
                                if (loginJSONArray.optJSONObject(0).has("DepartNo"))
                                    curDepartNo = loginJSONArray.optJSONObject(0).get("DepartNo").toString();
                                if (loginJSONArray.optJSONObject(0).has("Depart"))
                                    curDepart = loginJSONArray.optJSONObject(0).get("Depart").toString();
                                if (loginJSONArray.optJSONObject(0).has("PlaceCount"))
                                    curPlaceCount = loginJSONArray.optJSONObject(0).getInt("PlaceCount");
                                if (loginJSONArray.optJSONObject(0).has("LoginUser"))
                                    curLoginUser = loginJSONArray.optJSONObject(0).get("LoginUser").toString();
                                if (loginJSONArray.optJSONObject(0).has("LoginUserNo"))
                                    curLoginUserNo = loginJSONArray.optJSONObject(0).get("LoginUserNo").toString();
                                if (loginJSONArray.optJSONObject(0).has("LoginTime"))
                                    curLoginTime = loginJSONArray.optJSONObject(0).get("LoginTime").toString();
                                if (loginJSONArray.optJSONObject(0).has("OperateTime"))
                                    curOperateTime = loginJSONArray.optJSONObject(0).getInt("OperateTime");
                                if (loginJSONArray.optJSONObject(0).has("LoginType"))
                                    curLoginType = loginJSONArray.optJSONObject(0).getString("LoginType");
                                if (loginJSONArray.optJSONObject(0).has("UserPower"))
                                    curUserPower = loginJSONArray.optJSONObject(0).getString("UserPower");
                                if (loginJSONArray.optJSONObject(0).has("CurTime"))
                                    curTime = loginJSONArray.optJSONObject(0).getString("CurTime");
                                //登陆界面;
                                loginOK(curLoginType);
                            } else {
                                curToast.setText(getString(R.string.PleaseCheckEmpNoPSW));
                                curToast.show();
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                default:
                    break;
            }
        }
    };



    //API版本23以下时调用此方法进行检测
    //因为API23后getNetworkInfo(int networkType)方法被弃用
    public boolean checkNetState_21(){
        try {
            //步骤1：通过Context.getSystemService(Context.CONNECTIVITY_SERVICE)获得ConnectivityManager对象
            ConnectivityManager connMgr = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
            //步骤2：获取ConnectivityManager对象对应的NetworkInfo对象
            //NetworkInfo对象包含网络连接的所有信息
            //步骤3：根据需要取出网络连接信息
            //获取WIFI连接的信息
            NetworkInfo networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            Boolean isWifiConn = networkInfo.isConnected();
            //获取移动数据连接的信息
            networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            Boolean isMobileConn = networkInfo.isConnected();
            System.out.println("Wifi是否连接:" + isWifiConn + " 移动数据是否连接:" + isMobileConn);
            return isWifiConn || isMobileConn;
        } catch (Exception e){
            Toast.makeText(this,"checkNetState_21"+e.getMessage(),Toast.LENGTH_LONG).show();
            return true;
        }
    }


    //API版本23及以上时调用此方法进行网络的检测
    //步骤非常类似
    public boolean checkNetState_21orNew(){
        //获得ConnectivityManager对象
        boolean isConnect=false;
        try {
            ConnectivityManager connMgr = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
            //获取所有网络连接的信息
            Network[] networks = new Network[0];
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                networks = connMgr.getAllNetworks();
            }
            //用于存放网络连接信息
            StringBuilder sb = new StringBuilder();
            //通过循环将网络信息逐个取出来
            for (int i = 0; i < networks.length; i++) {
                //获取ConnectivityManager对象对应的NetworkInfo对象
                NetworkInfo networkInfo = null;
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                    networkInfo = connMgr.getNetworkInfo(networks[i]);
                }
                if (isConnect == false) isConnect = networkInfo.isConnected();

            }
            return isConnect;
        } catch (Exception e){
            Toast.makeText(this,"checkNetState_21orNew",Toast.LENGTH_LONG).show();
            return false;
        }
    }

    // 隐藏手机键盘
    private void hideIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) this.getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }




    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //当处理初始Fragment，则返回;
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            showTips();
        }
        return super.onKeyDown(keyCode, event);
    }
    //延时执行登陆校验
    private void LoginCheckDelay(){
        //隐藏键盘
        edit_LoginUserNo.setInputType(InputType.TYPE_NULL);
        hideBottomUIMenu();
        hideIM(edit_LoginUserNo);        //准备登陆;
        TimerTask task = new TimerTask() {
            @Override
            public void run() {

            }
        };
        Timer timer = new Timer();
        timer.schedule(task, 500);//3秒后执行TimeTask的run方法
    }
    //登陆校验;
    private void loginCheck(){
        String tmpPassword = "123";
        //登陆判断
        if (tmpPassword.length()>0) {
            // 在这里使用的是encode方式，返回的是byte类型加密数据，可使用new String转为String类型
            tmpPassword = new String(Base64.encode(tmpPassword.getBytes(), Base64.DEFAULT));
            Log.i("Test", "tmpPassword>>>" + tmpPassword);
        }
        edit_LoginUserNo.setInputType(InputType.TYPE_NULL);
        //组织WebService地址;
        String tmpServiceUrl=serviceUrl+serviceUrlExt;
        //调用登陆过程;
        String SqlComm="Exec ScenePAD_LoginCheck @UserNo='" + edit_LoginUserNo.getText().toString() + "',@PassWord='"+ tmpPassword.replaceAll("\r|\n", "")+"',@CPUID='"+CPUID+"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_LoginSYS:
                if (edit_LoginUserNo.getText().length()==0) {
                    curToast.setText(getString(R.string.PleaseInputEmpNo));
                    curToast.show();
                } else loginCheck();
                break;
            case R.id.btn_ExitSYS:
                showTips();
                break;
            case R.id.btn_guide_setup:
                showSetup();
                break;
            case R.id.btn_EditPass:
                edit_LoginUserNo.setInputType(InputType.TYPE_CLASS_NUMBER);
                //1.得到InputMethodManager对象
                InputMethodManager imm = (InputMethodManager) getSystemService(GuideActivity.this.INPUT_METHOD_SERVICE);
                //2.调用showSoftInput方法显示软键盘，其中view为聚焦的view组件
                imm.showSoftInput(edit_LoginUserNo,InputMethodManager.SHOW_FORCED);
                //changepsw();
                break;
            default:
                break;
        }

    }

    //登陆成功
    private void loginOK(String LoginType){
        //隐藏键盘
        edit_LoginUserNo.setInputType(InputType.TYPE_NULL);
        hideBottomUIMenu();
        hideIM(edit_LoginUserNo);
        //延时500毫秒
        new Thread(){
            public void run(){
                try {
                    sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();

        //跳转前关闭键盘
        Intent mainActivity  = new Intent(GuideActivity.this, MainActivity.class);
        //简单参数通过Intent的Extras传递;
        Bundle paramBundle = new Bundle();
        paramBundle.putString("LoginUserNo", curLoginUserNo);
        paramBundle.putString("LoginUser", curLoginUser);
        paramBundle.putString("CurFactory", curFactory);
        paramBundle.putString("CurDepartNO", curDepartNo);
        paramBundle.putString("CurDepart",curDepart);
        paramBundle.putInt("PlaceCount",curPlaceCount);
        paramBundle.putInt("OperateTime", curOperateTime);
        paramBundle.putString("serviceUrl", serviceUrl);
        paramBundle.putString("serviceUrlExt", serviceUrlExt);
        paramBundle.putString("CPUID",CPUID);
        paramBundle.putString("language",language);
        paramBundle.putString("UserPower",curUserPower);
        mainActivity.putExtras(paramBundle);
        if (waitDialog!=null) waitDialog.hide();

        //启动主界面;
        startActivity(mainActivity);


    }
    private void saveSetup(){
        //登陆成功后保存配置;
        SharedPreferences settings = getSharedPreferences(STORE_NAME, MODE_PRIVATE);
        SharedPreferences.Editor set_editor=settings.edit();
        set_editor.putString("LoginUserNo",edit_LoginUserNo.getText().toString());
        set_editor.putString("serviceUrl",serviceUrl);
        set_editor.putString("UrlApi",MyApplication.UrlApi);
        set_editor.putString("language",language);
        set_editor.commit();
    }
    private void showSetup(){
        //创建布局
        LayoutInflater inflater=this.getLayoutInflater();
        final View guide_setup=inflater.inflate(R.layout.guide_setup, null);
        //Activity.findViewById最终还是会调用View.findViewById
        //因为在Activity的onCreate中一定会先setContentView的
        final EditText text_serverUrl=(EditText)guide_setup.findViewById(R.id.text_serverUrl);
        text_serverUrl.setText(serviceUrl);
        final EditText text_apiUrl=(EditText)guide_setup.findViewById(R.id.text_apiUrl);
        text_apiUrl.setText(MyApplication.UrlApi);
        final RadioGroup languageRG=(RadioGroup)guide_setup.findViewById(R.id.languageRG);
        if (language.equals("zh")==true) languageRG.check(R.id.RB1);
        if (language.equals("en")==true) languageRG.check(R.id.RB2);
        if (language.equals("km")==true) languageRG.check(R.id.RB3);
        //创建对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(guide_setup).setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Log.v("tag",text_serverUrl.getText().toString());
                        serviceUrl=text_serverUrl.getText().toString();
                        MyApplication.UrlApi=text_apiUrl.getText().toString();
                        if (languageRG.getCheckedRadioButtonId()==R.id.RB1) language="zh";
                        if (languageRG.getCheckedRadioButtonId()==R.id.RB2) language="en";
                        if (languageRG.getCheckedRadioButtonId()==R.id.RB3) language="km";
                        System.out.println("语言:"+"---------------------"+language);
                        saveSetup();
                        hideIM(guide_setup);
                    }
                }
        ).setNegativeButton(getString(R.string.Cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                hideIM(guide_setup);
                Log.v("tag",getString(R.string.Cancel));
            }
        }).setTitle(getString(R.string.SoftTitle));
        builder.show();
    }

    //修改密码
    private void changepsw(){
        //创建布局
        LayoutInflater inflater=this.getLayoutInflater();
        final View guide_setup=inflater.inflate(R.layout.guide_changepsw, null);
        //Activity.findViewById最终还是会调用View.findViewById
        //因为在Activity的onCreate中一定会先setContentView的
        final EditText text_password_old=(EditText)guide_setup.findViewById(R.id.text_password_old);
        final EditText text_password_new=(EditText)guide_setup.findViewById(R.id.text_password_new);
        final EditText text_password_new2=(EditText)guide_setup.findViewById(R.id.text_password_new2);
        //创建对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(guide_setup).setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Field field = null;
                        hideIM(guide_setup);
                        String tmpOldPassword = text_password_old.getText().toString();
                        String tmpNewPassword = text_password_new.getText().toString();
                        String tmpNewPassword2 = text_password_new2.getText().toString();
                        Log.i("Test", "tmpOldPassword>>>" + tmpOldPassword+"----tmpNewPassword>>>" + tmpNewPassword+"----tmpNewPassword2>>>" + tmpNewPassword2);
                        if ((tmpNewPassword.length()>0) && (tmpNewPassword.equals(tmpNewPassword2))) {
                            try {
                                field = dialog.getClass().getSuperclass().getDeclaredField( "mShowing" );
                                field.setAccessible(true );
                                field.set(dialog,true );
                            } catch (NoSuchFieldException e) {
                                e.printStackTrace();
                            }
                            catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                            // 在这里使用的是encode方式，返回的是byte类型加密数据，可使用new String转为String类型
                            tmpNewPassword = Base64.encodeToString(tmpNewPassword.getBytes(), Base64.DEFAULT);
                            if (tmpOldPassword.length()>0) tmpOldPassword=Base64.encodeToString(tmpOldPassword.getBytes(), Base64.DEFAULT);
                            Log.i("Test", "tmpOldPassword>>>" + tmpOldPassword+"----tmpNewPassword>>>" + tmpNewPassword);
                            //组织WebService地址;
                            String tmpServiceUrl=serviceUrl+serviceUrlExt;
                            //调用登陆过程;
                            String SqlComm= "Exec ScenePAD_ChangePSW @UserNo='" + edit_LoginUserNo.getText().toString() + "',@OldPassWord='"+tmpOldPassword.replaceAll("\r|\n", "")+"',@NewPassWord='"+tmpNewPassword.replaceAll("\r|\n", "")+"'";
                            //调用WebService过程并处理界面更新;
                            ReadSQLData(SqlComm);
                        } else
                        {
                            try {
                                field = dialog.getClass().getSuperclass().getDeclaredField( "mShowing" );
                                field.setAccessible(true );
                                    field.set( dialog,false );
                            } catch (NoSuchFieldException e) {
                                e.printStackTrace();
                            }
                            catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                            curToast.setText(getString(R.string.PasswordConfirmErr));
                            curToast.show();
                        }
                    }
                }
        ).setNegativeButton(getString(R.string.Cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                try {
                    hideIM(guide_setup);
                    Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
                    field.setAccessible(true);
                    field.set(dialog,true); // true - 使之可以关闭(此为机关所在，其它语句相同)
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                }
                Log.v("tag",getString(R.string.Cancel));
            }
        }).setTitle(getString(R.string.SoftTitle));
        builder.show();
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (edit_LoginUserNo!=null) {
            edit_LoginUserNo.setFocusable(true);
            edit_LoginUserNo.setFocusableInTouchMode(true);
            edit_LoginUserNo.requestFocus();
            edit_LoginUserNo.requestFocusFromTouch();
        }
        checkNetTimer();
        //读取配置文件;
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        serviceUrl=sp.getString("ServiceURL",serviceUrl);
        MyApplication.UrlApi=sp.getString("UrlApi",MyApplication.UrlApi);



    }

    //获取软件版本;
    private String getVersionName() throws Exception
    {
        // 获取packagemanager的实例
        PackageManager packageManager = getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(),0);
        String version = packInfo.versionName;
        return version;
    }


    //获取CPU值
    public static String getLocalCPUID() {
        String resultSerial = null;
        String str = "";
        try {
            Process pp = Runtime.getRuntime().exec("cat /sys/devices/platform/cpu/uuid");
            InputStreamReader ir = new InputStreamReader(pp.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
            for (; null != str; ) {
                str = input.readLine();
                if (str != null) {
                    resultSerial = str.trim();// 去空格
                    break;
                }
            }
        } catch (IOException ex) {
            // 赋予默认值
            ex.printStackTrace();
        }
        return resultSerial;
    }


}
